<?php

/**
 *  后台继承类
 * @file   Admin.php  
 * @date   2016-8-23 19:45:21 
 * @author Zhenxun Du<5552123@qq.com>  
 * @version    SVN:$Id:$ 
 */

namespace app\index\controller;
use app\admin\model\User as UserModel;
use think\Config;
use think\Loader;
use think\Request;

class User extends Common {

    public function index() {
        $where = [];
        $name = input('name');

        if($name){

            $where1['A.true_name'] = [['like',"%{$name}%"]];
            $where2['A.mobile'] = $name;

        }


        $field = "A.id,A.role_id,A.mobile,A.user_name,A.true_name,A.create_at,A.last_login_at,A.sex,B.name as company_name";


        $lists = db("user")->alias("A")->field($field)
            ->join("cy_company B","A.com_id=B.id","left")

            ->where($where1)->whereOr($where2)->where($where)->order("A.id desc")->paginate(20);

        $this->assign('lists', $lists);

        $this->assign('name', $name);
        return $this->fetch();
    }

    /*
           * 查看
           */

    public function info() {

        $id = input('id');

        $company = db('company')->select();
        if ($id) {
            //当前用户信息
            $info = db('user')->where(['id'=>$id])->find();
            $this->assign('info', $info);
        }
        $this->assign('company', $company);
        $this->assign('id', $id);

        return $this->fetch();
    }

    /*
     * 添加
     */

    public function add() {
        $post = input();
        //验证数据
        if(!isset($post['user_name'])  || !$post['user_name']){
            $this->error('用户名不能为空');
        }
        if(!isset($post['true_name'])  || !$post['true_name']){
            $this->error('用户真实姓名不能为空');
        }
        if(!isset($post['password'])  || !$post['password']){
            $this->error('登录密码不能为空');
        }
        if(!isset($post['mobile'])  || !$post['mobile']){
            $this->error('手机号不能为空');
        }
        if(!isset($post['com_id'])  || !$post['com_id']){
            $this->error('企业id不能为空');
        }
        if(!isset($post['role_id']) || !$post['role_id']){
            $this->error('角色不能为空');
        }
        //验证用户是否已注册
        $userModel = new UserModel();
        $user = $userModel->getUserName($post['user_name']);

        if($user){
            $this->error('该用户名已存在');
        }
        $arr['create_at'] = time();

        $password_hash =  password_hash($post['password'], PASSWORD_DEFAULT);

        $arr['user_name'] = $post['user_name'];
        $arr['true_name'] = $post['true_name'];

        $arr['mobile'] = $post['mobile'];
        $arr['password_hash'] = $password_hash;
        $arr['com_id'] = $post['com_id'];
        $arr['role_id'] = $post['role_id'];
        $arr['create_at'] = time();
        $request = Request::instance();
        $arr['create_ip'] = $request->ip();
        $arr['update_at'] = time();
        $arr['contact_address'] = $post['contact_address'];

        //添加数据后同步至本地服务器
        $baseUrl =  Config::get('loal_api_url');
        $setUrl = $baseUrl."/api/User/addUser";

        $sysArr['user_name'] = $arr['user_name'];
        $sysArr['password'] = $arr['password_hash'];
        $statusArr = $this->synUserData($sysArr,$setUrl);
        if($statusArr['code']!=200){
//            return json_encode(['code' => 400, "msg" =>$statusArr['msg']]);
            $this->error($statusArr['msg']);

        }

        if($userModel->insert($arr)!==false){

            $this->success('操作成功', url('index'));
        }else{
            $this->error('操作失败');
        }


    }

    /*
     * 修改
     */

    public function edit() {
        $post = input();

        //验证数据
        if(!isset($post['id'])  || !$post['id']){
            $this->error('用户名id不能为空');
        }
        if(!isset($post['user_name'])  || !$post['user_name']){
            $this->error('用户名不能为空');
        }
        if(!isset($post['true_name'])  || !$post['true_name']){
            $this->error('用户真实姓名不能为空');
        }

        if(!isset($post['mobile'])  || !$post['mobile']){
            $this->error('手机号不能为空');
        }
        if(!isset($post['com_id'])  || !$post['com_id']){
            $this->error('企业id不能为空');
        }
        if(!isset($post['role_id']) || !$post['role_id']){
            $this->error('角色不能为空');

        }
        //验证用户是否已注册
        $userModel = new UserModel();
        $user = $userModel->getUserName($post['user_name'],$post['id']);

        if($user){
            $this->error('该用户名已存在');
        }

        if(isset($post['password']) && $post['password']){
            $password_hash =  password_hash($post['password'], PASSWORD_DEFAULT);
            $arr['password_hash'] = $password_hash;
        }

        $arr['user_name'] = $post['user_name'];
        $arr['true_name'] = $post['true_name'];
        $arr['mobile'] = $post['mobile'];
        $arr['com_id'] = $post['com_id'];
        $arr['role_id'] = $post['role_id'];
        $arr['update_at'] = time();
        $arr['contact_address'] = $post['contact_address'];
        //修改数据后同步至本地服务器

        $baseUrl =  Config::get('loal_api_url');
        $setUrl = $baseUrl."/api/User/editUser";
        $whereUserInfo['id'] = $post['id'];
        $userInfo = $userModel->getUserInfo($whereUserInfo);

        $synArr['old_user_name'] = $userInfo['user_name'];
        $synArr['user_name'] = $arr['user_name'];
        $synArr['password'] = $arr['password_hash']?$arr['password_hash']:$userInfo['password_hash'];

        $statusArr = $this->synUserData($synArr,$setUrl);
        if($statusArr['code']!=200){
//                return json_encode(['code' => 400, "msg" =>$statusArr['msg']]);

            $this->error($statusArr['msg']);

        }


        if($userModel->where(['id'=>$post['id']])->update($arr)!==false){
            $this->success('操作成功', url('index'));
        }else{

            $this->error('编辑失败');
        }

    }

    /*
     * 删除
     */

    public function del() {
        $id = input('id');

        $res = db('user')->where(['id' => $id])->delete();
        if ($res) {

            $this->success('操作成功', url('index'));
        } else {
            $this->error('操作失败');
        }
    }
    //同步数据
    public function synUserData($arr,$setUrl){

        $baseUrl = Config::get('loal_api_url');
        $url = $baseUrl."/api/index/getToken";
        $sarrJson = $this->curl_post($url,[]);
        if(!$sarrJson){
            return  ['code'=>0,'msg'=>'数据同步获取token失败'];
        }
        $sarr = json_decode($sarrJson,true);
        if(!isset($sarr['code']) || $sarr['code'] != 200){
            return  ['code'=>0,'msg'=>'数据同步获取token失败了'];
        }
        $token = $sarr['data']['token'];
        $larr['old_user_name'] = isset($arr['old_user_name']) && $arr['old_user_name']?$arr['old_user_name']:'';
        $larr['user_name'] = $arr['user_name'];
        $larr['password'] = $arr['password'];
        $larr['encrypt'] = '';
        $larr['service_url'] = Config::get('base_url');
        $larr['project'] = 'sampling_cat';

        $larrJson = $this->curl_post($setUrl,$larr,$token);

        if(!$larrJson){
            return  ['code'=>0,'msg'=>'同步用户数据失败'];
        }
        $synArr = json_decode($larrJson,true);
        if(!isset($synArr['code']) || $synArr['code'] != 200){
            return  ['code'=>0,'msg'=>$synArr['msg']];
        }
        return  ['code'=>200,'msg'=>'成功'];
    }
    //数据同步
    public function curl_post($url,$array,$token=''){

        $curl = curl_init();
        //设置提交的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = $array;
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

        if($token!=''){
            $headers[]  =  "Accept:application/json";
            $headers[]  = "Authorization: Bearer ". $token;
            if(!empty($headers)){
                curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );

            }
        }

        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //获得数据并返回
        return $data;
    }
}
